package drds.configuration.mvc.util.filter;


import drds.configuration.common.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

/**
 * 静态资源缓存.filter-mapping不能为/*.否则jstl标签使用的时候会出问题
 */
public class StaticResourseCacheFilter implements Filter {

    private HashMap<String, String> expiresMap = new HashMap<String, String>();

    public void init(FilterConfig filterConfig) {
        Properties properties = new Properties();
        InputStream in = StaticResourseCacheFilter.class
                .getResourceAsStream("StaticResourseCacheFilter.properties");
        try {
            properties.load(in);
        } catch (IOException e) {
            throw new RuntimeException("静态资源文件不存在");
        }
        expiresMap.putAll(expiresMap);
    }


    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain chain) throws IOException, ServletException {
        /**
         * 开发阶段不使用
         */
        if (!Constants.devMode) {// if (!Constants.devMode) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            // 任何请求的地址：包括图片、JS
            String uri = request.getRequestURI();
            String extention = null;// 扩展名
            int dot = uri.lastIndexOf(".");
            if (dot != -1) {// 从最后一个开始截
                extention = uri.substring(dot + 1);
            }
            /**
             * \只对/*中静态资源处理
             */
            if (expiresMap.containsKey(extention)) {
                setResponseHeader(response, uri, extention);
            }
        }
        chain.doFilter(servletRequest, servletResponse);

    }


    private void setResponseHeader(HttpServletResponse response, String uri, String extention) {
        if (extention != null && extention.length() > 0) {
            Integer expireTime = Integer.parseInt((String) expiresMap.get(extention));
            if (expireTime != null) {
                if (expireTime.intValue() > 0) {
                    response.setHeader("Cache-Control", "max-age=" + expireTime.intValue());
                } else {
                    response.setHeader("Cache-Control", "no-cache");
                    response.setHeader("Pragma", "no-cache");
                    response.setDateHeader("Expires", 0);
                }
            }
        }
    }

    public void destroy() {
    }
}